package com.wispx.gateway.config.helper;

import com.wispx.gateway.config.manager.DynamicConfigManager;
import com.wispx.gateway.config.pojo.RouteDefinition;

import java.util.*;
import java.util.regex.Pattern;

public class RouteResolver {

    private static final DynamicConfigManager manager = DynamicConfigManager.getInstance();

    private RouteResolver(){

    }

    /**
     * 根据uri解析路由
     * @param uri 待解析的uri
     * @return 匹配到的路由（yaml中配置）
     */
    public static RouteDefinition matchRoute(String uri){
        Set<Map.Entry<String/*uri*/, RouteDefinition>> routeEntrySet = manager.allUriRouteEntrySet();
        List<RouteDefinition> matchedRoute = new ArrayList<>();
        for (Map.Entry<String, RouteDefinition> entry : routeEntrySet) {
            String regex = entry.getKey().replace("**", ".*");// 用于正则
            if (Pattern.matches(regex,uri)){
                matchedRoute.add(entry.getValue());
            }
        }
        if (matchedRoute.isEmpty()) {
            throw new RuntimeException("没有匹配到路由");
        }
        matchedRoute.sort(Comparator.comparingInt(RouteDefinition::getOrder));
        return matchedRoute.stream()
                .min(Comparator.comparingInt(RouteDefinition::getOrder)
                                .thenComparing(route -> route.getUri().length(),Comparator.reverseOrder()))
                .orElseThrow();
    }

}
